/*
 * Copyright (C) 2004, Velocityme Partnership
 * StateSessionBean.java
 *
 * Created on 15 March 2004, 09:45
 */

package com.velocityme.session;

import com.velocityme.entity.ChangeDeltaItemTypeBean;
import com.velocityme.entity.ChangeDeltaTypeBean;
import com.velocityme.entity.PermissionBean;
import javax.ejb.*;
import javax.naming.*;
import java.util.*;
import com.velocityme.interfaces.*;
import com.velocityme.utility.InvalidKeyException;
import com.velocityme.utility.PermissionDeniedException;
import com.velocityme.valueobjects.*;
import java.rmi.RemoteException;

/**
 *
 * @author  Robert
 * @ejb.bean
 *           type="Stateless"
 *           cmp-version="2.x"
 *           name="StateSession"
 *           jndi-name="ejb/StateSession"
 *           view-type="local"
 *           transaction-type="Container"
 * @ejb.transaction type="Required"
 *
 * @ejb.util generate="physical"
 */
public class StateSessionBean implements SessionBean {
    
    private SessionContext m_context;
    
    private SearchSessionLocal m_searchSessionLocal;

    private PermissionLocal m_permissionStateCreate;
    private PermissionLocal m_permissionStateEdit;
    private PermissionLocal m_permissionNodeView;

    /**
     * If the user has permission to create a new State in the specified parent
     * node then go ahead and create it and log an appropriate ChangeDelta.
     *
     * @param p_key User's security key
     * @param p_parentNode The node which will contain the new State
     * @param p_stateValue The value details for the State part of the state
     *
     * @ejb.interface-method view-type="local"
     **/
    public StateLocal createState(KeySessionLocal p_keyLocal,
                                  NodeLocal p_parentNodeLocal,
                                  com.velocityme.valueobjects.StateValue p_stateValue)
        throws PermissionDeniedException, InvalidKeyException {
        try {
            if (m_searchSessionLocal.getAssignedPermissionsLocal(p_keyLocal, p_parentNodeLocal).contains(m_permissionStateCreate)) {
                p_stateValue.getNodeValue().setType("State");
                p_stateValue.getNodeValue().setFinalType("State");
                DBObjectLocal dBObjectLocal = DBObjectUtil.getLocalHome().create();
                NodeValue nodeValue = p_stateValue.getNodeValue();
                NodeLocal nodeLocal = NodeUtil.getLocalHome().create(dBObjectLocal, nodeValue, p_parentNodeLocal);
                nodeValue.setNodeId(nodeLocal.getNodeId());
                StateLocal stateLocal = StateUtil.getLocalHome().create(nodeLocal, p_stateValue);
                ChangeDeltaLocal changeDeltaLocal = ChangeDeltaUtil.getLocalHome().create(new Date(), ChangeDeltaTypeBean.CREATE, p_keyLocal.getUserLocal(), dBObjectLocal);
                changeDeltaLocal.addItem(ChangeDeltaItemTypeBean.NAME, nodeValue.getName());
                changeDeltaLocal.addItem(ChangeDeltaItemTypeBean.DESCRIPTION, nodeValue.getDescription());
                changeDeltaLocal.addItem(ChangeDeltaItemTypeBean.ACTIVE, p_stateValue.getIsActive().toString());
                changeDeltaLocal.addItem(ChangeDeltaItemTypeBean.PARENT_NODE, p_parentNodeLocal.getPathName());
                return stateLocal;
            }
            else
                throw new PermissionDeniedException();
        }
        catch(NamingException e) {
            throw new EJBException(e);
        }
        catch(CreateException e) {
            throw new EJBException(e);
        }
    }
    
    /**
     * If the user has permission to edit the State then do so and log the
     * changes with an appropriate ChangeDelta.
     *
     * @param p_key User's security key
     * @param p_statePK The State object being editted
     * @param p_stateValue The value details for the State part of the state
     *
     * @ejb.interface-method view-type="local"
     **/
    public void editState(KeySessionLocal p_keyLocal,
                          StateLocal p_stateLocal,
                          com.velocityme.valueobjects.StateValue p_stateValue)
        throws PermissionDeniedException, InvalidKeyException {
        try {
            NodeLocal nodeLocal = p_stateLocal.getNodeLocal();
            if (m_searchSessionLocal.getAssignedPermissionsLocal(p_keyLocal, nodeLocal).contains(m_permissionStateEdit)) {
                NodeValue nodeValue = p_stateValue.getNodeValue();
                ChangeDeltaLocal changeDeltaLocal = ChangeDeltaUtil.getLocalHome().create(new Date(), ChangeDeltaTypeBean.EDIT, p_keyLocal.getUserLocal(), nodeLocal.getDBObjectLocal());
                if (!nodeValue.getName().equals(nodeLocal.getName()))
                    changeDeltaLocal.addItem(ChangeDeltaItemTypeBean.NAME, nodeValue.getName());
                if (!nodeValue.getDescription().equals(nodeLocal.getDescription()))
                    changeDeltaLocal.addItem(ChangeDeltaItemTypeBean.DESCRIPTION, nodeValue.getDescription());
                if (!p_stateValue.getIsActive().equals(p_stateLocal.getIsActive()))
                    changeDeltaLocal.addItem(ChangeDeltaItemTypeBean.ACTIVE, p_stateValue.getIsActive().toString());
                nodeLocal.setNodeValue(nodeValue);
                p_stateLocal.setStateValue(p_stateValue);
            }
            else
                throw new PermissionDeniedException();
        }
        catch(NamingException e) {
            throw new EJBException(e);
        }
        catch(CreateException e) {
            throw new EJBException(e);
        }
    }
    
    /**
     * Get the start state value object.
     *
     * @param p_key User's security key
     *
     * @ejb.interface-method view-type="local"
     **/
    public com.velocityme.valueobjects.StateValue getStartStateValueObject(com.velocityme.interfaces.KeySessionLocal p_keyLocal)
        throws InvalidKeyException {
        StateValue startStateValue = null;
        try {
            if (p_keyLocal.isValid())
                startStateValue = new StateValueToString(StateUtil.getLocalHome().findStartState().getStateValue());
            else
                throw new InvalidKeyException();
        }
        catch(NamingException e) {
            throw new EJBException(e);
        }
        catch(FinderException e) {
            throw new EJBException(e);
        }
        return startStateValue;
    }
    
    /**
     * Get the full list of status value objects.
     *
     * @param p_key User's security key
     *
     * @ejb.interface-method view-type="local"
     **/
    public com.velocityme.valueobjects.StateValue[] getAllValueObjects(com.velocityme.interfaces.KeySessionLocal p_keyLocal) throws InvalidKeyException {
        StateValue[] values = null;
        try {
            if (p_keyLocal.isValid()) {
                Collection states = StateUtil.getLocalHome().findAll();
                values = new StateValue[states.size()];
                int j = 0;
                Iterator i = states.iterator();
                while(i.hasNext()) {
                    StateLocal stateLocal = (StateLocal)i.next();
                    values[j++] = new StateValueToString(stateLocal.getStateValue());
                }
            }
            else
                throw new InvalidKeyException();
        }
        catch(NamingException e) {
            throw new EJBException(e);
        }
        catch(FinderException e) {
            throw new EJBException(e);
        }
        return values;
    }
    
    /**
     * Get the list of state value objects associated with a task.
     *
     * @param p_key User's security key
     *
     * @ejb.interface-method view-type="local"
     **/
    public com.velocityme.valueobjects.StateValue[] getTaskStateValueObjects(com.velocityme.interfaces.KeySessionLocal p_keyLocal,
                                                                             com.velocityme.interfaces.TaskLocal p_taskLocal) throws InvalidKeyException {
        StateValue[] values = null;
        try {
            if (p_keyLocal.isValid()) {
                Collection states = StateUtil.getLocalHome().findByTask(p_taskLocal);
                values = new StateValue[states.size()];
                int j = 0;
                Iterator i = states.iterator();
                while(i.hasNext()) {
                    StateLocal stateLocal = (StateLocal)i.next();
                    values[j++] = new StateValueToString(stateLocal.getStateValue());
                }
            }
            else
                throw new InvalidKeyException();
        }
        catch(NamingException e) {
            throw new EJBException(e);
        }
        catch(FinderException e) {
            throw new EJBException(e);
        }
        return values;
    }
    
    /**
     * Create the Session Bean.
     * @throws CreateException 
     * @ejb:create-method view-type="remote"
     */
    public void ejbCreate() throws CreateException {
        try {
            m_searchSessionLocal = SearchSessionUtil.getLocalHome().create();
            m_permissionStateCreate = PermissionUtil.getLocalHome().findByPrimaryKey(new PermissionPK(new Integer(PermissionBean.STATE_CREATE)));
            m_permissionStateEdit = PermissionUtil.getLocalHome().findByPrimaryKey(new PermissionPK(new Integer(PermissionBean.STATE_EDIT)));
            m_permissionNodeView = PermissionUtil.getLocalHome().findByPrimaryKey(new PermissionPK(new Integer(PermissionBean.NODE_VIEW)));
        }
        catch(NamingException e) {
            throw new CreateException(e.getMessage());
        }
        catch(FinderException e) {
            throw new CreateException(e.getMessage());
        }
    }

    public void ejbActivate() throws java.rmi.RemoteException {
    }
    
    public void ejbPassivate() throws java.rmi.RemoteException {
    }
    
    public void ejbRemove() throws java.rmi.RemoteException {
    }
    
    public void setSessionContext(javax.ejb.SessionContext sessionContext) throws java.rmi.RemoteException {
        m_context = sessionContext;
    }
    
}
